package cn.bm.web.controllers.user;

import cn.bm.web.services.UserServices;
import spark.Route;

import static spark.Spark.get;
import static spark.Spark.post;

// req 封装 servlet
public class UserController {
    static Route login = (req, res)->{    //定义了一个静态路由处理器，用于处理登录请求
        // 设置session
        String username = req.queryParams("username");
        String password = req.queryParams("password");

        System.out.println(username + " " + password);
        if(username==null || password==null){
            res.redirect("/login.html");
            return "/login.html";
        }
        Boolean loginSuccessful = UserServices.login(username,password);
        System.out.println("logined:"+loginSuccessful);
        if(!loginSuccessful){
            res.redirect("/login.html");//如果登录失败，重定向到登录页面 (/login.html)
        }else {
            req.session().attribute("username",username);//如果登录成功，将用户名存储在会话中
            res.redirect("/test.html");
        }
        return "login";
    };

    static Route register = (req, res) ->{
        // 设置session
        String username = req.queryParams("username");
        String password = req.queryParams("password");
        String recheckpassword = req.queryParams("recheckpassword");
        if(username==null || password==null || recheckpassword==null){
            res.redirect("/register.html");
            return "register";
        }
        System.out.println(username + " " + password + " " + recheckpassword);
        Boolean registerSuccessful = UserServices.register(username,password,recheckpassword);
        System.out.println("register:"+registerSuccessful);
        if(!registerSuccessful){
            res.redirect("/register.html");//如果注册失败，重定向到注册页面 (/register.html)
        }else {
            res.redirect("/login.html");
            req.session().attribute("username",username);//如果注册成功，将用户名存储在会话中
        }
        System.out.println(username + " " + password);
        return "register";
    };

    static Route test = (req,res)->{     //定义了一个静态路由处理器，用于测试请求
        System.out.println(req.ip());
        req.session().attribute("user","none");

        return "test";
        //打印请求的 IP 地址，并在会话中设置一个名为 user 的属性为 "none"
    };

    public static void InitRoutes() {

        /**
         * 开放访问
         */
        System.out.println("init user controller");
        get("/user/login",login);     //处理登录请求
        post("/user/register",register);     // 处理注册请求
        /**
         * 授权后访问
         */
        get("/app/test", test);//处理测试请求
    }
}
